package com.terrynoya.fight.evaluation
{
	import com.terrynoya.fight.emuns.Operator;
	import com.terrynoya.fight.emuns.SymbolType;
	import com.terrynoya.fight.util.Integer;

	public class ParseState
	{
		private var _system:EvaluationSystem;
		private var _node:Node;
		private var _tokens:Array;
		private var _initIndex:int;
		private var _currentIndex:int;
		private var _build:TreeBuilder;
		
		public function ParseState(system:EvaluationSystem,build:TreeBuilder,node:Node,tokens:Array,index:int)
		{
			this._system = system;
			this._build = build;
			this._node = node;
			this._tokens = tokens;
			this._initIndex = index;
			this._currentIndex = index;
		}
		
		public function buildParenNumberNode(frombase:Boolean):Node
		{
			var savedindex:int = this.tokenIndex;
			if(this.currentSymbol != SymbolType.LeftParen)
			{
				this.tokenIndex = savedindex;
				return null;
			}
			this.tokenIndex++;
			var node:Node = this.buildNode(true);
			if(node == null)
			{
				this.tokenIndex = savedindex;
				return null;
			}
			
			if(this.currentSymbol != SymbolType.RightParen)
			{
				this.tokenIndex = savedindex;
				return null;
			}
			this.tokenIndex++;
			
			if(frombase)
			{
				this.baseNode.chilren.push(node);
				return this.baseNode;
			}
			else
			{
				return node;
			}
		}
		
		public function buildNode(full:Boolean):Node
		{
			var index:Integer = new Integer(this.tokenIndex);
			var node:Node = null;
			if(full)
			{
				node = this._build.parseNode(this._tokens,index);
			}
			else
			{
				node = this._build.parseEndNode(this._tokens,index);
			}
			this._currentIndex = index.value;
			return node;
		}
		
		public function get baseNode():Node 
		{
			return this._node;
		}
		
		public function get tokenIndex():int 
		{
			return this._currentIndex;
		}
		
		public function set tokenIndex(value:int):void
		{
			this._currentIndex = value;
		}
		
		public function get currentToken():Token 
		{
			if(this._currentIndex < 0 || this._currentIndex >= this._tokens.length)
			{
				return null;
			}
			return this._tokens[this._currentIndex];
		}
		
		public function get currentSymbol():String 
		{
			if(this.currentToken == null)
			{
				return SymbolType.None;
			}
			return this.currentToken.asSymbol;
		}
		
		public function get currentUnknown():String 
		{
			if(this.currentToken == null)
			{
				return null;
			}
			return this.currentToken.asUnknown;
		}
		
		public function get currentText():String 
		{
			if(this.currentToken == null)
			{
				return null;
			}
			return this.currentToken.asText;
		}
		
		public function get currentOperator():int 
		{
			if(this.currentToken == null)
			{
				return Operator.None;
			}
			else
			{
				return this.currentToken.asOperator;
			}
		}
	}
}